import fs from 'fs';
import symbol from 'log-symbols';
import chalk from 'chalk';
import inquirer from 'inquirer';
import downloadGit from 'download-git-repo';
const path = require('path');

// 文件是否存在
let notExistFold = async(name, check) => {
    return new Promise((resolve) => {
        if (fs.existsSync(name)) {
            if (check) {
                resolve(true);
            } else {
                console.log(symbol.error, chalk.greenBright('文件夹名已被占用，请更换名字重新创建'));
            }
        } else {
            resolve();
        }
    });
}

// 询问用户
let promptList = [{
        type: 'list',
        name: 'frame',
        message: '选择模板或者现有测试项目',
        choices: ['single', 'sites']
    },
    {
        type: 'input',
        name: 'description',
        message: '输入该项目描述: '
    },
    {
        type: 'input',
        name: 'author',
        message: '请输入您的大名: '
    }
];

let prompt = () => {
    return new Promise(resolve => {
        inquirer
            .prompt(promptList)
            .then(answer => {
                resolve(answer);
            })
    });
}

// 项目模板远程下载
let downloadTemplate = async(ProjectName, api) => {
    return new Promise((resolve, reject) => {
        downloadGit(api, ProjectName, { clone: true }, (err) => {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        })
    });
};

// 更新json配置文件
let updateJsonFile = (fileName, obj) => {

    return new Promise(resolve => {
        if (fs.existsSync(fileName)) {
            const data = fs.readFileSync(fileName).toString();
            let json = JSON.parse(data);
            Object.keys(obj).forEach(key => {
                json[key] = obj[key];
            });
            fs.writeFileSync(fileName, JSON.stringify(json, null, '\t'), 'utf-8');
            resolve();
        }
    });
}

// 询问用户运行项目
let runPromptList = [{
    type: 'list',
    name: 'frame',
    message: '选择需要运行或打包的站点',
    choices: []
}];

let devPrompt = () => {
    return new Promise(resolve => {
        inquirer
            .prompt(runPromptList)
            .then(answer => {
                resolve(answer);
            })
    });
}

// 获取需要进行运行或打包的工程
let getRunPath = () => {
    const isSingle = fs.readdirSync(path.resolve('./')).indexOf('sites') === -1;

    if (isSingle) return false;

    return new Promise(async(resolve) => {
        // 获取路径
        var files = fs.readdirSync(path.resolve('sites'))

        if (files.length === 0) {
            console.log(symbol.error, chalk.greenBright('没有站点可以运行或打包，请新建站点'));
        } else {
            runPromptList[0].choices = files;
            var site = await devPrompt();
            resolve(site.frame);
        }
    })
}

let addSites = (siteName, ProjectName) => {
    ProjectName = ProjectName ? ProjectName : '';

    fs.mkdirSync(path.resolve(`${ProjectName}sites`) + `/${siteName}`);
    fs.writeFileSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/main.js`, 'console.log("Hellow World")');

    fs.mkdirSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/pug`);
    fs.writeFileSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/pug/首页.pug`, 'p Hellow World')

    fs.mkdirSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/pug/part`);
    fs.writeFileSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/pug/part/.gitkeep`, '')

    fs.mkdirSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/pug/public`);
    fs.writeFileSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/pug/public/header.pug`, '.head ')
    fs.writeFileSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/pug/public/footer.pug`, '.foot ')
    fs.writeFileSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/pug/public/layout.pug`, fs.readFileSync(path.resolve(`${ProjectName}src`) + `/pug/public/layout.pug`, 'utf8'))
    fs.mkdirSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/images`);
    fs.writeFileSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/images/.gitkeep`, '')

    fs.mkdirSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/js`);
    fs.writeFileSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/js/.gitkeep`, '')

    fs.mkdirSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/css`);
    fs.writeFileSync(path.resolve(`${ProjectName}sites`) + `/${siteName}/css/.gitkeep`, '')
}

module.exports = {
    notExistFold,
    prompt,
    downloadTemplate,
    updateJsonFile,
    getRunPath,
    addSites
}
